﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebVideo.Models;
using MvcLibrary.Repository;
using System.Net;
namespace WebVideo.Controllers
{
    public class LoginUserController : Controller
    {
        //
        // GET: /LoginUser/

        public ActionResult Index()
        {
            return View();
        }
        #region "DangKy"
        public ActionResult DangKy(string User)
        {

            LoginUserModel dk = new LoginUserModel();
            dk.Link = User;
            return View(dk);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult DangKy(LoginUserModel DK)
        {

            try
            {
                dbVideoDataContext db = new dbVideoDataContext();

                string ipaddress;
                ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (ipaddress == "" || ipaddress == null)
                    ipaddress = Request.ServerVariables["REMOTE_ADDR"];
                DK.Ip = ipaddress;
                var dsip = db.EntityUsers.Where(g => g.Ip == ipaddress);
                if (dsip.ToList().Count >= 3)
                {
                    ModelState.AddModelError("UserName", "Địa chỉ IP đã đăng ký đủ số lượng account");
                }
                else
                {
                    var query = db.EntityBusinesses.Where(g => g.UserName == DK.UserName);
                    var query1 = db.EntityBusinesses.Where(g => g.Email == DK.Email);
                    var query3 = db.EntityUsers.Where(g => g.UserName == DK.UserName);
                    var query4 = db.EntityUsers.Where(g => g.Email == DK.Email);
                    if (query.ToList().Count > 0 || query3.ToList().Count > 0)
                    {
                        ModelState.AddModelError("UserName", "UserName đã tồn tại");
                    }
                    else if (query1.ToList().Count > 0 || query4.ToList().Count > 0)
                    {
                        ModelState.AddModelError("Email", "Email đã tồn tại");
                    }
                }
                if (ModelState.IsValid)
                {
                    LoginUserModel.DangKy(DK);
                    return RedirectToAction("Mailer", "Mailer", new { User = DK.UserName });
                   
                }
            }
            catch
            {

                return RedirectToAction("Index", "Error");
            }
            return View(DK);
        }
        #endregion //insert

       #region "login logout"
        public JsonResult CheckId(string username, string pass, bool Remember)
        {
            LoginModel m = new LoginModel();
            m.UserName = " ";
            dbVideoDataContext db = new dbVideoDataContext();
            Security ser = new Security();
            string passHex = ser.GetHashPassword(pass);
            var adminquery = from p in db.EntityUsers
                             where p.UserName == username && p.Pass == passHex && (p.Status == 2 || p.Status == 1 || p.Status == 0 || p.Status == 3)
                             select p;
            if (adminquery.ToList().Count == 1)
            {
                if ((int)adminquery.First().Status == 0 || (int)adminquery.First().Status == 3 || (int)adminquery.First().Status == 2)
                {
                    m.Status = (int)adminquery.First().Status;
                    return Json(m);
                }
                else 
                {
                    m.UserName = adminquery.First().UserName;
                    m.Avatar = adminquery.First().Avatar;
                    m.Status = (int)adminquery.First().Status;

                    Response.Cookies["UserId"].Value = adminquery.First().UserName;
                    Response.Cookies["UserAvatar"].Value = adminquery.First().Avatar;
                    Response.Cookies["UserType"].Value = "1";
                    GiaHanCookie(Remember);
                }      

            }
            else
            {

                var adminquery1 = from p in db.EntityBusinesses
                                  where p.UserName == username && p.Pass == passHex && (p.Status == 2 || p.Status == 1)
                                  select p;
                if (adminquery1.ToList().Count == 1)
                {
                    m.UserName = adminquery1.First().UserName;
                    m.Avatar = adminquery1.First().Avatar;
                    m.Status = (int)adminquery1.First().Status;

                    Response.Cookies["UserId"].Value = adminquery1.First().UserName;
                     
                    Response.Cookies["UserAvatar"].Value = adminquery1.First().Avatar;
                    Response.Cookies["UserType"].Value = "2";
                    GiaHanCookie(Remember);

                }
                else
                {
                    m.Status = 4;
                }

            }
            
            return Json(m);
        }
        public void GiaHanCookie(bool Remember)
        {
            if (Remember == true)
            {
               Response.Cookies["UserId"].Expires = DateTime.Now.AddDays(7);
               Response.Cookies["UserAvatar"].Expires = DateTime.Now.AddDays(7);
               Response.Cookies["UserType"].Expires = DateTime.Now.AddDays(7);
            } 
        }
        public ActionResult logout()
        {
            if (Request.Cookies["UserId"] != null)
            {
                //xoa username
                var c = new HttpCookie("UserId");
                c.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(c);
                // xoa avatar
                var d = new HttpCookie("UserAvatar");
                d.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(d);

                var t = new HttpCookie("UserType");
                d.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(d);
            }

            // Session["AdminId"] = null; // Xoa session       
            return RedirectToAction("Index", "Index");
        }
        #endregion //login logout

        #region "kichhoat"
        public ActionResult KH(LoginUserModel khoat, string User)
        {
            try
            {
                LoginUserModel.KH(khoat,User);
                return RedirectToAction("KichHoatThanhCong", "LoginUser");

            }
            catch
            {
                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });

            }
        }
        public ActionResult KichHoatTaiKhoan()
        {
            return View();
        }
        public ActionResult KichHoatThanhCong()
        {
            return View();
        }
        public ActionResult Ban()
        {
            return View();
        }
        public ActionResult ChuaKH()
        {
            return View();
        }
        public ActionResult Xoa()
        {
            return View();
        }
        #endregion
        #region "Quen mat khau"
        public ActionResult QuenMatKhau()
        {
            return View();
        }
        public ActionResult KhoiPhuc(string Email)
        {
            dbVideoDataContext db = new dbVideoDataContext();
                
                var query = db.EntityUsers.Where(g => g.Email == Email);

                var query1 = db.EntityBusinesses.Where(g => g.Email == Email);

                if (query.ToList().Count > 0 || query1.ToList().Count > 0)
                {
                    return RedirectToAction("KhoiPhuc", "Mailer", new { Email = Email });
                }
                else
                {
                    return RedirectToAction("ErrorMail", "LoginUser");
                }
       
        }
        public ActionResult SaiEmail()
        {
            return View();
        }

        public string ErrorMail()
        {
            return "error";
        }
        public ActionResult DaGuiKPMK()
        {
            return View();
        }

        public ActionResult KPMK(string User )
        {
            ForgetPassModel tnew = new ForgetPassModel();
            tnew.Link = User;
            return View(tnew);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult KPMK(ForgetPassModel khoat)
        {
          
                try
                {
                    if (ModelState.IsValid)
                    {

                        ForgetPassModel.KP(khoat);
                        return RedirectToAction("KichHoatThanhCong", "LoginUser");

                    }
                }
                catch
                {
                    return RedirectToAction("Error", "Index");

                }
                return View(khoat);
        }

        #endregion
    }
}
